package com.htgd.gardenexpo.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import com.htgd.gardenexpo.dto.CarbonChangeDTO;
import com.htgd.gardenexpo.entity.*;
import com.htgd.gardenexpo.page.PageBase;
import com.htgd.gardenexpo.page.WxUserQuery;
import com.htgd.gardenexpo.service.GeConIntegralGetDetailsService;
import com.htgd.gardenexpo.service.GeConIntegralGetService;
import com.htgd.gardenexpo.service.WxUserCouponService;
import com.htgd.gardenexpo.service.WxUserService;
import com.htgd.gardenexpo.utils.TokenUtil;
import com.htgd.gardenexpo.vo.IntegralDetailsVO;
import com.htgd.gardenexpo.vo.UserNumVO;
import com.htgd.gardenexpo.vo.WxUserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/api/wxUser")
@Api( tags = "微信用户")
@Slf4j
public class WxUserController {
    @Autowired
    private WxUserService wxUserService;
    @Value("${upload.absolute.head}")
    private String absolute_url;

    @Value("${local.url}")
    public String local_url;

    @Autowired
    private WxUserCouponService wxUserCouponService;

    @Autowired
    private GeConIntegralGetService geConIntegralGetService;

    @Autowired
    private GeConIntegralGetDetailsService geConIntegralGetDetailsService;

    @GetMapping("/getUserById")
    @ApiOperation("通过id获取微信用户")
    public CommonResult<WxUserVO>  getUserById(String userId){
        CommonResult<WxUserVO> result = new CommonResult<>();
        QueryWrapper<WxUser> queryWrapper=new QueryWrapper<>();
        WxUser wxUser=wxUserService.getOne(queryWrapper.eq("user_id",userId));
        if(null==wxUser){
            result.setCode(500);
        }else {
            result.setCode(200);
            WxUserVO wxUserVO = new WxUserVO();
            BeanUtils.copyProperties(wxUser,wxUserVO);
            result.setData(wxUserVO);
        }
        return result;
    }




    @PostMapping("/add")
    @ApiOperation("添加微信用户")
    public CommonResult<JSONObject> add (@RequestBody WxUser wxUser){
        CommonResult<JSONObject> result = new CommonResult<>();
        wxUserService.save(wxUser);
        result.setCode(200);
        result.setMessage("新增成功");
        return result;

    }

    @PostMapping("/edit")
    @ApiOperation("修改微信用户")
    @Transactional
    public CommonResult<JSONObject> edit (@RequestBody WxUser wxUser){
        log.info("修改微信用户：{}",wxUser);
        return wxUserService.edit(wxUser);
    }


    @PostMapping(value = "/upload")
    @ApiOperation("上传用户头像")
    public String upload(@RequestParam(value = "file") MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            System.out.println("文件为空");
        }

        BufferedImage image = ImageIO.read(file.getInputStream());
        int width = 0 ;
        int height = 0;
        if (image != null) {
            width = image.getWidth();
            height = image.getHeight();
        }

        String fileName = file.getOriginalFilename();  // 文件名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));  // 后缀名
        String filePath = absolute_url; // 上传后的路径
        fileName = UUID.randomUUID() + "@" + width +"@"+ height +"@"+ suffixName; // 新文件名
        File dest = new File(filePath + fileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return local_url+"head/"+fileName;
    }



    @PostMapping("/getPhoneNumber")
    @ApiOperation("通过code获取手机号")
    public Object getPhoneNumber(@RequestBody Map<String,Object> data) {
        return wxUserService.getPhoneNumber(data);
    }

    @ApiOperation("获取openid")
    @GetMapping(value = "/getOpenId")
    public String getOpenId(String code){
        return wxUserService.getOpenId(code);
    }

    @GetMapping("/login")
    @ApiOperation("授权登录")
    public CommonResult<WxUser> login(String code) {
        CommonResult<WxUser> result = new CommonResult<>();
        String openId = getOpenId(code);
//        String openId = "dsdsd";
        WxUser wxUser = wxUserService.login(openId);

        GeBaseUser geBaseUser = new GeBaseUser();
        geBaseUser.setPhone(wxUser.getOpenId());
        String token = TokenUtil.sign(geBaseUser);
        wxUser.setToken(token);

        wxUserService.updateToken(token,wxUser);

        result.setCode(200);
        result.setData(wxUser);
        return result;
    }

    @PostMapping("/bindPhone")
    @ApiOperation("绑定手机号")
    public CommonResult bindPhone(@RequestBody JSONObject jsonObject) {
        log.info("微信用户-绑定手机号：{}",jsonObject);
        return wxUserService.bindPhone(jsonObject);
    }

    @GetMapping(value = "/list")
    @ApiOperation("查询")
    public CommonResult<List<WxUserVO>> list(WxUserQuery wxUserQuery) {
        CommonResult<List<WxUserVO>> result = new CommonResult<>();
        try {
            PageInfo<WxUserVO> list = wxUserService.querylist(wxUserQuery);
            result.setCode(200);
            result.setData(list.getList());
            result.setMessage(String.valueOf(list.getTotal()));
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    @GetMapping(value = "/getNum")
    @ApiOperation("获取各种数量")
    public CommonResult<UserNumVO> getNum(HttpServletRequest request) {
        CommonResult<UserNumVO> result = new CommonResult<>();
        try {
            String accessToken = request.getHeader("Access_token");
            String openId = TokenUtil.getUsernameFromToken(accessToken);
            //优惠券数
            Integer couponNum = wxUserCouponService.getCouponNum(openId);
            //碳积分
//            CommonResult<JSONObject> userScore = carbonMobileTask.getUserScore(openId);
            UserNumVO userNumVO = wxUserService.getNum(openId);
            userNumVO.setCouponNum(couponNum);
            result.setCode(200);
            result.setData(userNumVO);
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }



    @GetMapping(value = "/getIntegralDetails")
    @ApiOperation("获取积分明细")
    public CommonResult<List<IntegralDetailsVO>> getIntegralDetails(PageBase pageBase, HttpServletRequest request) {
        CommonResult<List<IntegralDetailsVO>> result = new CommonResult<>();
        try {
            Map<String,Object> map = new HashMap<>();
            String accessToken = request.getHeader("Access_token");
            String openId = TokenUtil.getUsernameFromToken(accessToken);
            PageInfo<IntegralDetailsVO> list = geConIntegralGetDetailsService.getIntegralDetails(openId,pageBase);
            result.setCode(200);
            result.setMessage(String.valueOf(list.getTotal()));
            result.setData(list.getList());
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    @GetMapping(value = "/getRegisterNums")
    @ApiOperation("获取小程序人数")
    public CommonResult getRegisterNums(String date) {
        log.info("综管-获取小程序人数:{}",date);
         return wxUserService.getRegisterNums(date);
    }

    @GetMapping(value = "/getDailyActivityCount")
    @ApiOperation("获取小程序日活跃数")
    public CommonResult getDailyActivityCount(@RequestParam(value = "beginDate") String beginDate,
                                              @RequestParam(value = "endDate") String endDate) {
        log.info("综管-获取小程序日活跃数:{},{}",beginDate,endDate);
        return wxUserService.getDailyActivityCount(beginDate,endDate);
    }

    @GetMapping(value = "/getPhoneCityNums")
    @ApiOperation("获取小程序号码归属地")
    public CommonResult getPhoneCityNums() {
        log.info("综管-获取小程序号码归属地");
        return wxUserService.getPhoneCityNums();
    }

    @PostMapping(value = "/bindFace")
    @ApiOperation("甲板通知小程序人脸绑定信息")
    public CommonResult bindFace(@RequestBody JSONObject body) {
        log.info("甲板通知小程序人脸绑定信息：{}",body);
        return wxUserService.bindFace(body);
    }

    @DeleteMapping(value = "/unbindFace")
    @ApiOperation("解绑人脸")
    public CommonResult unbindFace(HttpServletRequest request) {
        String accessToken = request.getHeader("Access_token");
        String openId = TokenUtil.getUsernameFromToken(accessToken);
        log.info("解绑人脸：{}",openId);
        return wxUserService.unbindFace(openId);
    }

}
